<?php
/*
Plugin Name: Shopp Subscription Engine
Version: 0.1.0
Description: Integrates with the Shopp plugin to help facilitate digital subscription services. <strong>Shopp (1.2 or greater) must be activated</strong> for this plugin to work!
Author: Barry Hughes
Author URI: http://freshlybakedwebsites.net

	Shopp Subscription Engine: members only plugin for WordPress and Shopp
    Copyright (C) 2012 Barry Hughes

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program. If not, see <http://www.gnu.org/licenses/>.
*/


// Build on top of the Shopp Extension Scaffold.
require_once(dirname(__FILE__).'/inc/scaffold.php');


/**
 * Facilitates selling access to all or select content on a WordPress
 * website through integration with the Shopp plugin.
 * 
 * @author Barry Hughes
 * @copyright 2012 Barry Hughes
 * @version 0.1.0
 */
class ShoppSE extends ShoppSE_Scaffold
{
	/**
	 * Declares the version of scaffolding this plugin was
	 * built for.
	 */
	const SCAFFOLDING = '0.1.0';

	/** 
	 * Plugin name.
	 */
	const PLUGIN_NAME = 'Shopp Subscription Engine';

	/**
	 * Defining $plugin_file allows us to separate out the
	 * extension scaffolding from the Shopp Magazine Engine class
	 * file.
	 * 
	 * @var string
	 */
	public $plugin_file;
	
	/**
	 * Plugin directory path.
	 * 
	 * @var string
	 */
	public $plugin_dir;
	
	/**
	* Plugin URL.
	* 
	* @var string
	*/
	public $plugin_url;
	
	/**
	 * Settings module.
	 * 
	 * @var ShoppSE_Settings
	 */
	public $settings;
	
	/**
	 * Users module.
	 * 
	 * @var ShoppSE_Users
	 */
	public $users;
	
	
	
	/**
	 * Sets up the Shopp Magazine Engine.
	 * 
	 * Facilitates housing the extension scaffold in a separate file.
	 * All other construction work takes place within the scaffold.
	 * 
	 * @return Shopp_Magazine
	 */
	public function __construct()
	{
		// Self-locate
		$this->plugin_dir = dirname(__FILE__);
		$this->plugin_file = '/'.basename(__FILE__);
		$this->plugin_url = WP_PLUGIN_URL.'/'.basename(dirname(__FILE__));

		// Extension scaffolding
		parent::__construct();
	}
	
	
	/**
	 * Set up the Shopp Magazine Engine.
	 */
	public function begin()
	{
		// Required class files
		require_once("{$this->plugin_dir}/inc/content.php");
		require_once("{$this->plugin_dir}/inc/settings.php");
		require_once("{$this->plugin_dir}/inc/users.php");
		
		// Create supporting objects
		$this->content = new ShoppSE_Content($this);
		$this->users = new ShoppSE_Users($this);
		
		// Add a settings page
		$this->add_setup_page('shoppse_admin', 'ShoppSE_Settings', 'Site Subscriptions');
        
		// Register hooks
		add_action('shopp_order_success', array($this, 'order_completed'));
	}
	
	
	/**
	 * Examines the purchase for subscription products.
	 * 
	 * @param Purchase $purchase
	 */
	public function order_completed(Purchase $purchase)
	{		
		// Sanity check: the $purchased array must be populated
		if (empty($purchase->purchased)) return;

		// Scan for purchased subscriptions
		foreach ($purchase->purchased as $item) 
			if ($item->type === 'Subscription')
				$this->record_subscription($item);
	}
	
	
	/**
	 * Attempts to locate the related WordPress user account and
	 * inserts a meta record to mark the subscription details.
	 * 
	 * The $item object is expected to represent a record from
	 * the shopp_purchased table.
	 * 
	 * @param stdClass $purchase_id
	 */
	protected function record_subscription(stdClass $purchased)
	{
		// Safely attempt to determine the WP user associated with purchase
		try
		{
			$purchase = new Purchase($purchased->purchase);
			$customer = new Customer($purchase->customer);
			$wpuser = (int) $customer->wpuser;
		}
		catch (Exception $e) { $fail = $e; }

		// Test for failure: log and exit flow if necessary
		if (isset($fail) or $wpuser < 1) 
		{
			if (SHOPP_DEBUG and isset($fail)) new ShoppError($fail->getMessage(), false, SHOPP_DEBUG_ERR);
			new ShoppError('Related WP user account could not be found. Subscription abandoned.', false, SHOPP_AUTH_ERR);
			return;
		}

		// Load the price and annotate the user record
		$price = new Price($purchased->price);

		// Check that the price record loaded
		if (!$price->exists())
			new ShoppError('Subscription price record could not be found. Subscription abandoned.', 
				false, SHOPP_ADMIN_ERR);
		
		// Otherwise lets mark up the user record
		else $this->users->markup_user_record($wpuser, $purchased->created, $price);
	}               
}


// Start!
new ShoppSE;